<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证件类型" prop="idType">
        <el-select v-model="queryParams.idType" placeholder="请选择证件类型" clearable>
          <el-option
            v-for="dict in dict.type?.id_type || []"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="证件号码" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入证件号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['travel:customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['travel:customer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['travel:customer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="small"
          @click="handleExport"
          v-hasPermi="['travel:customer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户ID" align="center" prop="customerId" />
      <el-table-column label="客户姓名" align="center" prop="customerName" />
      <el-table-column label="证件类型" align="center" prop="idType">
        <template #default="scope">
          <dict-tag :options="dict.type?.id_type || []" :value="scope.row.idType"/>
        </template>
      </el-table-column>
      <el-table-column label="证件号码" align="center" prop="idNumber" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          <dict-tag :options="dict.type?.sys_user_sex || []" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="phone" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="dict.type?.sys_normal_disable || []" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['travel:customer:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['travel:customer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="证件类型" prop="idType">
          <el-select v-model="form.idType" placeholder="请选择证件类型">
            <el-option
              v-for="dict in dict.type?.id_type || []"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio
              v-for="dict in dict.type?.sys_user_sex || []"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker clearable
            v-model="form.birthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="国籍" prop="nationality">
          <el-input v-model="form.nationality" placeholder="请输入国籍" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="身份证正面" prop="idCardFront">
          <image-upload
            v-model="form.idCardFront"
            @ocrData="handleOcrFront"
          />
        </el-form-item>
        <el-form-item label="身份证背面" prop="idCardBack">
          <image-upload
            v-model="form.idCardBack"
            @ocrData="handleOcrBack"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type?.sys_normal_disable || []"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer, exportCustomer } from "@/api/travel/customer";
import { useDict } from '@/hooks/useDict'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download } from '@element-plus/icons-vue'
import { getRefs, resetForm, download } from '@/utils/ruoyi'
import ImageUpload from '@/components/ImageUpload/index.vue'
import { ocrIdCard, ocrIdCardAlt, ocrIdCardJson } from '@/api/travel/customer'

const { dict } = useDict(['sys_normal_disable', 'sys_user_sex', 'id_type'])

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 客户信息表格数据
const customerList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  customerName: null,
  idType: null,
  idNumber: null,
  phone: null,
  status: null
})
// 表单参数
const form = ref({
  customerId: null,
  customerName: null,
  idType: null,
  idNumber: null,
  gender: null,
  birthday: null,
  nationality: null,
  address: null,
  phone: null,
  email: null,
  idCardFront: null,
  idCardBack: null,
  status: "0",
  remark: null
})
// 表单校验
const rules = ref({
  customerName: [
    { required: true, message: "客户姓名不能为空", trigger: "blur" }
  ],
  idType: [
    { required: true, message: "证件类型不能为空", trigger: "change" }
  ],
  idNumber: [
    { required: true, message: "证件号码不能为空", trigger: "blur" }
  ],
  phone: [
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  email: [
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
  ]
})

/** 查询客户信息列表 */
function getList() {
  loading.value = true
  listCustomer(queryParams.value).then(response => {
    customerList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    customerId: null,
    customerName: null,
    idType: null,
    idNumber: null,
    gender: null,
    birthday: null,
    nationality: null,
    address: null,
    phone: null,
    email: null,
    idCardFront: null,
    idCardBack: null,
    status: "0",
    remark: null
  }
  resetForm("form")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  resetForm("queryForm")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.customerId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加客户信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const customerId = row.customerId || ids.value
  getCustomer(customerId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改客户信息"
  })
}

/** 提交按钮 */
function submitForm() {
  getRefs("form").validate(valid => {
    if (valid) {
      if (form.value.customerId != null) {
        updateCustomer(form.value).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCustomer(form.value).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const customerIds = row.customerId || ids.value
  ElMessageBox.confirm('是否确认删除客户信息编号为"' + customerIds + '"的数据项？').then(function() {
    return delCustomer(customerIds)
  }).then(() => {
    getList()
    ElMessage.success("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  download('travel/customer/export', {
    ...queryParams.value
  }, `customer_${new Date().getTime()}.xlsx`)
}

// 处理身份证正面 OCR
const handleOcrFront = (base64) => {
  console.log('接收到正面身份证图片数据，准备发送 OCR 请求')
  
  if (!base64) {
    console.error('身份证图片数据为空')
    ElMessage.error('图片数据为空，无法进行 OCR 识别')
    return
  }
  
  // 检查图片数据格式
  let imageData = base64
  
  // 确保 base64 数据格式正确
  if (base64.startsWith('data:image')) {
    // 提取纯base64内容
    imageData = base64.split(',')[1]
    console.log('提取纯base64数据，长度:', imageData.length)
  } else {
    console.log('图片数据没有data:image前缀，直接使用')
  }
  
  console.log('发送 OCR 请求，数据长度:', imageData.length)
  ElMessage.info('正在识别身份证，请稍候...')
  
  // 依次尝试三种方式
  tryOcrMethods(imageData, 1);
}

// 尝试不同的OCR方法
const tryOcrMethods = (imageData, attempt) => {
  console.log(`尝试第 ${attempt} 种OCR方法`);
  
  let ocrPromise;
  
  if (attempt === 1) {
    // 第一种方式：纯文本
    ocrPromise = ocrIdCard(imageData);
  } else if (attempt === 2) {
    // 第二种方式：FormData
    ocrPromise = ocrIdCardAlt(imageData);
  } else if (attempt === 3) {
    // 第三种方式：JSON
    ocrPromise = ocrIdCardJson(imageData);
  } else {
    ElMessage.error('OCR识别失败，已尝试所有可用方法');
    return;
  }
  
  ocrPromise
    .then(res => {
      console.log(`第 ${attempt} 种OCR方法结果:`, res);
      // axios 直接返回的结构与 request 不同，需要获取 data 字段
      const response = res.data;
      if (response.code === 200 && response.data) {
        handleOcrSuccess(response.data);
      } else {
        throw new Error(response.msg || 'OCR识别失败');
      }
    })
    .catch(error => {
      console.error(`第 ${attempt} 种OCR方法失败:`, error);
      ElMessage.info(`正在尝试第 ${attempt + 1} 种方式识别...`);
      // 递归尝试下一种方法
      tryOcrMethods(imageData, attempt + 1);
    });
}

// OCR 识别成功后处理数据
const handleOcrSuccess = (data) => {
  try {
    if (!data) {
      ElMessage.warning('OCR识别结果为空');
      return;
    }
    
    console.log('OCR 识别成功，处理结果数据:', data);
    form.value.customerName = data.name || '';
    form.value.idNumber = data.idNumber || data.id_number || '';
    
    // 性别可能有不同的表示方式
    if (data.gender) {
      form.value.gender = data.gender === '男' ? '1' : '2';
    } else if (data.sex) {
      form.value.gender = data.sex === '男' ? '1' : '2';
    }
    
    // 可能还有其他字段需要处理
    if (data.birthday) {
      form.value.birthday = data.birthday;
    }
    if (data.address) {
      form.value.address = data.address;
    }
    
    ElMessage.success('OCR识别成功');
  } catch (error) {
    console.error('处理 OCR 结果数据时出错:', error)
    ElMessage.error('处理 OCR 数据失败: ' + error.message)
  }
}

// 处理身份证背面 OCR
const handleOcrBack = (base64) => {
  console.log('接收到背面身份证图片数据，准备发送 OCR 请求')
  
  if (!base64) {
    console.error('身份证图片数据为空')
    ElMessage.error('图片数据为空，无法进行 OCR 识别')
    return
  }
  
  // 检查图片数据格式
  let imageData = base64
  
  // 确保 base64 数据格式正确
  if (base64.startsWith('data:image')) {
    // 提取纯base64内容
    imageData = base64.split(',')[1]
    console.log('提取纯base64数据，长度:', imageData.length)
  } else {
    console.log('图片数据没有data:image前缀，直接使用')
  }
  
  console.log('发送背面 OCR 请求，数据长度:', imageData.length)
  ElMessage.info('正在识别身份证背面，请稍候...')
  
  // 依次尝试三种方式
  tryOcrBackMethods(imageData, 1);
}

// 尝试不同的OCR方法（背面）
const tryOcrBackMethods = (imageData, attempt) => {
  console.log(`尝试第 ${attempt} 种OCR方法（背面）`);
  
  let ocrPromise;
  
  if (attempt === 1) {
    // 第一种方式：纯文本
    ocrPromise = ocrIdCard(imageData);
  } else if (attempt === 2) {
    // 第二种方式：FormData
    ocrPromise = ocrIdCardAlt(imageData);
  } else if (attempt === 3) {
    // 第三种方式：JSON
    ocrPromise = ocrIdCardJson(imageData);
  } else {
    ElMessage.error('OCR背面识别失败，已尝试所有可用方法');
    return;
  }
  
  ocrPromise
    .then(res => {
      console.log(`第 ${attempt} 种OCR背面方法结果:`, res);
      // axios 直接返回的结构与 request 不同，需要获取 data 字段
      const response = res.data;
      if (response.code === 200 && response.data) {
        console.log('身份证背面数据:', response.data);
        ElMessage.success('OCR背面识别成功');
      } else {
        throw new Error(response.msg || 'OCR背面识别失败');
      }
    })
    .catch(error => {
      console.error(`第 ${attempt} 种OCR背面方法失败:`, error);
      ElMessage.info(`正在尝试第 ${attempt + 1} 种方式识别背面...`);
      // 递归尝试下一种方法
      tryOcrBackMethods(imageData, attempt + 1);
    });
}

onMounted(() => {
  getList()
})
</script> 